package com.oracle.lingshangejia.activity;


import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import com.oracle.lingshangejia.Constant;
import com.oracle.lingshangejia.MyApp;
import com.oracle.lingshangejia.R;
import com.oracle.lingshangejia.adapter.FieledMissionsFragmentPagerAdapter;
import com.oracle.lingshangejia.base.BaseActivity;
import com.oracle.lingshangejia.bean.RecordTakingBean;
import com.oracle.lingshangejia.dialog.DoctorVideoDialog;
import com.oracle.lingshangejia.fragment.RecordOfConsultationsFragment;
import com.oracle.lingshangejia.fragment.RecordtakingrecordsFragment;
import com.oracle.lingshangejia.fragment.ReferralRecordsFragment;
import com.oracle.lingshangejia.utils.LastClickUtils;
import com.oracle.lingshangejia.utils.MyToast;
import com.oracle.lingshangejia.utils.OkHttpUtils;
import com.oracle.lingshangejia.utils.SpUtils;

import net.lucode.hackware.magicindicator.MagicIndicator;
import net.lucode.hackware.magicindicator.ViewPagerHelper;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.CommonNavigator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.CommonNavigatorAdapter;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerIndicator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerTitleView;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.indicators.LinePagerIndicator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.titles.ColorTransitionPagerTitleView;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.titles.SimplePagerTitleView;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

import io.agora.AgoraAPI;
import io.agora.AgoraAPIOnlySignal;
import io.agora.IAgoraAPI;

/**
 * 接诊详情
 */
public class FieledMissionsActivity extends BaseActivity implements View.OnClickListener {
    private MagicIndicator fiel_magic_indicator;
    private final int REQUEST_CODE = 0x01;
    private ViewPager fiel_view_pager;
    private TextView tv_title;
    private ImageButton ib_back;
    private  String[] CHANNELS = new String[]{"接诊记录", "会诊记录","转诊记录"};
    private List<String> mDataList = Arrays.asList(CHANNELS);
    private ArrayList<Fragment> fragments;
    private TextView tv_consultation;
    private TextView tv_trans;
    private int jmid;
    private int jzid;
    private String name;
    private boolean haverollin;  //是否有转入详情
    private boolean haverollout; //是否有转出详情
    private boolean havehz;//是否有会诊
   // private LinearLayout ll_bottom_f;
    private AgoraAPIOnlySignal mAgoraAPI;
    private String mPhone; //手机号当前登录用户
    private String channelName = "";
    private RecordtakingrecordsFragment mRecordtakingrecordsFragment;
    private RecordTakingBean mRecordTakingBean = new RecordTakingBean();

    @Override
    public int intiLayout() {
        return R.layout.activity_fieldmissions;
    }

    @Override
    public void initView() {
        fiel_magic_indicator=findViewById(R.id.fiel_magic_indicator);
        fiel_view_pager=findViewById(R.id.fiel_view_pager);
        tv_title=findViewById(R.id.tv_title);
        tv_title.setText("接诊详情");
        ib_back=findViewById(R.id.ib_back);
        ib_back.setOnClickListener(this);
        tv_consultation=findViewById(R.id.tv_consultation);
        tv_consultation.setOnClickListener(this);
        tv_trans=findViewById(R.id.tv_trans);
        //ll_bottom_f=findViewById(R.id.ll_bottom_f);
        tv_trans.setOnClickListener(this);
        jmid=getIntent().getIntExtra("jmid",0);
        jzid=getIntent().getIntExtra("jzid",0);
        name=getIntent().getStringExtra("name");
    }

    @Override
    public void initData() {

        fragments=new ArrayList<>();
        Bundle bundle = new Bundle();
        bundle.putInt("jmid",jmid);//这里的values就是我们要传的值
        bundle.putInt("jzid",jzid);//这里的values就是我们要传的值
        bundle.putString("name",name);
        mRecordtakingrecordsFragment = new RecordtakingrecordsFragment();
        RecordOfConsultationsFragment recordOfConsultationsFragment=new RecordOfConsultationsFragment();
        ReferralRecordsFragment referralRecordsFragment=new ReferralRecordsFragment();
        mRecordtakingrecordsFragment.setArguments(bundle);
        recordOfConsultationsFragment.setArguments(bundle);
        referralRecordsFragment.setArguments(bundle);
        fragments.add(mRecordtakingrecordsFragment);
        fragments.add(recordOfConsultationsFragment);
        fragments.add(referralRecordsFragment);
        FieledMissionsFragmentPagerAdapter mExamplePagerAdapter = new FieledMissionsFragmentPagerAdapter(getSupportFragmentManager(),fragments);
        fiel_view_pager.setAdapter(mExamplePagerAdapter);
        initMagicIndicator();
        getNetWorkHaveData();
        getNetWork1();
        getNetWork();
        mAgoraAPI = MyApp.the().getmAgoraAPI();
        mPhone = (String) SpUtils.get(this,"s_phone","");

        if (mAgoraAPI.getStatus()!=2){

            mAgoraAPI.login2(getString(R.string.agora_app_id), mPhone, "_no_need_token", 0, "", 5, 1);

        }
       // addCallback();
    }

    @Override
    protected void onResume() {
        super.onResume();
        addCallback();
    }

    private void addCallback() {
        MyApp.the().getmAgoraAPI().callbackSet(new AgoraAPI.CallBack() {

            @Override
            public void onLoginSuccess(int i, int i1) {
                Log.i(TAG, "onLoginSuccess " + i + "  " + i1);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {

                    }
                });
            }

            @Override
            public void onLoginFailed(final int i) {
                Log.i(TAG, "onLoginFailed " + i);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (i == IAgoraAPI.ECODE_LOGIN_E_NET) {

                        }
                    }
                });
            }


            @Override
            public void onError(String s, int i, String s1) {
                Log.i(TAG, "onError s:" + s + " s1:" + s1);
            }

        });



        if (mAgoraAPI == null) {
            return;
        }

        mAgoraAPI.callbackSet(new AgoraAPI.CallBack() {

            @Override
            public void onLogout(final int i) {
                Log.i(TAG, "onLogout  i = " + i);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (i == IAgoraAPI.ECODE_LOGOUT_E_KICKED) { // other login the account
                            //Toast.makeText(ExpertVideoActivity.this, "Other login account, you are logout.", Toast.LENGTH_SHORT).show();

                        } else if (i == IAgoraAPI.ECODE_LOGOUT_E_NET) { // net
                            //Toast.makeText(ExpertVideoActivity.this, "Logout for Network can not be.", Toast.LENGTH_SHORT).show();

                        }

                    }
                });

            }

            @Override
            public void onLoginFailed(int i) {
                Log.i(TAG, "onLoginFailed  i = " + i);
            }



            //专家端收到呼叫回调
            @Override
            public void onInviteReceivedByPeer(final String channelID, final String account, int uid) {//call out other local receiver
                Log.i(TAG, "onInviteReceivedByPeer  channelID = " + channelID + "  account = " + account);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        dismissLoading();
                        Intent intent = new Intent(FieledMissionsActivity.this, CallActivity.class);
                        intent.putExtra("account", mPhone);
                        intent.putExtra("channelName", channelID);
                        intent.putExtra("subscriber", account);
                        intent.putExtra("type", Constant.CALL_OUT);
                        startActivityForResult(intent, REQUEST_CODE);
                    }
                });

            }

            //如果呼叫失败，会回调 onInviteFailed。可能的原因有：
            //对方不在线
            //本端网络不通
            //服务器异常
            @Override
            public void onInviteFailed(String channelID, String account, int uid, int i1, String s2) {
                Log.i(TAG, "onInviteFailed  channelID = " + channelID + " account = " + account + " s2: " + s2 + " i1: " + i1);
            }

            @Override
            public void onError(final String s, int i, final String s1) {
                Log.e(TAG, "onError s = " + s + " i = " + i + " s1 = " + s1);

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {

                    }
                });
            }

            ///该回调返回用户状态查询结果。调用 queryUserStatus 方法时触发此回调。
            @Override
            public void onQueryUserStatusResult(final String name, final String status) {
                Log.i(TAG, "onQueryUserStatusResult name = " + name + " status = " + status);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {

                        if (status.equals("1")) {

                            if (!TextUtils.isEmpty(mRecordTakingBean.getData().getZjPhone())){
                                channelName = mPhone + mRecordTakingBean.getData().getZjPhone() ;

                                mAgoraAPI.channelInviteUser(channelName,mRecordTakingBean.getData().getZjPhone() , 0);
                            }else {
                                MyToast.show("网络错误");
                            }
                        } else if (status.equals("0")) {
                            dismissLoading();
                           Toast.makeText(FieledMissionsActivity.this,  " 专家不在线 ", Toast.LENGTH_SHORT).show();
                        }


                    }
                });
            }

        });
    }



    /**
     * 判断有没有会诊详情
     */
    private void getNetWorkHaveData() {
        int ysid= (int) SpUtils.get(FieledMissionsActivity.this,"ysid",0);
        HashMap<Object, Object> map = new HashMap<>();
        map.put("ysid",ysid);
        map.put("jzid",jzid);
        map.put("jmid",jmid);
        OkHttpUtils.getNetWork(FieledMissionsActivity.this, Constant.baseurl+"online/jzzz/hzjlDetail",map,handler);
    }
    private Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case 1:  //成功S
                    String s= (String) msg.obj;
                    if(!s.contains("id")){  //没有会诊信息
                      //  tv_consultation.setVisibility(View.VISIBLE);
                        havehz=false;
                    }else{ //有会诊信息
                    //    tv_consultation.setVisibility(View.GONE);
                        havehz=true;
                    }
                    break;
            }
        }
    };
    /**
     * 转入请求网络 判断是否有转入信息
     */
    private void getNetWork1() {
        int ysid= (int) SpUtils.get(FieledMissionsActivity.this,"ysid",0);
        HashMap<Object, Object> map = new HashMap<>();
        map.put("jmId",jmid);
        map.put("jzid",jzid);
        map.put("ysid",ysid);
        OkHttpUtils.getNetWork(FieledMissionsActivity.this, Constant.baseurl+"online/jzzz/sxzzzrDetail",map,handler1);
    }
    private Handler handler1=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case 1:  //成功S
                    String s= (String) msg.obj;
                    if(s.contains("id")){  //有转入详情
                        haverollin=true;
                    }else{
                        haverollin=false;
                    }
                    break;
            }
        }
    };
    /**
     * 转出请求网络
     */
    private void getNetWork() {
        int ysid= (int) SpUtils.get(FieledMissionsActivity.this,"ysid",0);
        HashMap<Object, Object> map = new HashMap<>();
        map.put("jmId",jmid);
        map.put("jzid",jzid);
        map.put("ysid",ysid);
        OkHttpUtils.getNetWork(FieledMissionsActivity.this, Constant.baseurl+"online/jzzz/sxzzzcDetail",map,handler2);
    }
    private Handler handler2=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case 1:  //成功S
                    String s= (String) msg.obj;
                    if(s.contains("id")){
                        haverollout=true;
                    }else{
                        haverollout=false;
                    }
                    if((!haverollin)&&(!haverollout)){
                        tv_trans.setVisibility(View.VISIBLE);
                    }else{
                       // tv_trans.setVisibility(View.GONE);
                    }
                    break;
            }
        }
    };
    private void initMagicIndicator() {
        CommonNavigator commonNavigator = new CommonNavigator(this);
        commonNavigator.setAdjustMode(true);
        commonNavigator.setAdapter(new CommonNavigatorAdapter() {

            @Override
            public int getCount() {
                return 3;
            }

            @Override
            public IPagerTitleView getTitleView(Context context, final int index) {
                SimplePagerTitleView simplePagerTitleView = new ColorTransitionPagerTitleView(context);
                simplePagerTitleView.setNormalColor(getResources().getColor(R.color.colorBlack));
                simplePagerTitleView.setSelectedColor(getResources().getColor(R.color.colorBlue));
                simplePagerTitleView.setText(mDataList.get(index));
                simplePagerTitleView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        fiel_view_pager.setCurrentItem(index);
                    }
                });
                return simplePagerTitleView;
            }

            @Override
            public IPagerIndicator getIndicator(Context context) {
                LinePagerIndicator linePagerIndicator = new LinePagerIndicator(context);
                linePagerIndicator.setMode(LinePagerIndicator.MODE_WRAP_CONTENT);
                linePagerIndicator.setColors(getResources().getColor(R.color.colorBlue));
                return linePagerIndicator;
            }
        });
        fiel_magic_indicator.setNavigator(commonNavigator);
        ViewPagerHelper.bind(fiel_magic_indicator, fiel_view_pager);
    }
    private String mDoctor;//专家医生手机号
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.ib_back:
                finish();
                break;
            case R.id.tv_consultation:
              //会诊
                if (LastClickUtils.isLastClick("慢点点哦")) {
                    showLoading();
                    mDoctor = mRecordtakingrecordsFragment.getRecordTakingBean().getData().getZjPhone();
                    mRecordTakingBean = mRecordtakingrecordsFragment.getRecordTakingBean();
                    if (TextUtils.isEmpty(mDoctor)){
                        DoctorVideoDialog doctorVideoDialog = new DoctorVideoDialog();
                        Bundle bundle = new Bundle();
                        bundle.putInt("jzid",jzid );//接诊id
                        doctorVideoDialog.setArguments(bundle);
                        doctorVideoDialog.setListener(new DoctorVideoDialog.Listener() {
                            @Override
                            public void select(String id) {
                                       mDoctor =id;
                                       mRecordtakingrecordsFragment.getRecordTakingBean().getData().setZjPhone(id);
                                       mAgoraAPI.queryUserStatus(mDoctor);
                            }
                        });
                        doctorVideoDialog.show(getSupportFragmentManager(), "");
                    }else {
                        mRecordTakingBean = mRecordtakingrecordsFragment.getRecordTakingBean();
                        mAgoraAPI.queryUserStatus(mDoctor);
                    }


                }
               /* if (LastClickUtils.isLastClick("慢点点哦")) {

                    if (!TextUtils.isEmpty(mRecordtakingrecordsFragment.getRecordTakingBean().getData().getZjPhone())){
                        showLoading();
                        mRecordTakingBean = mRecordtakingrecordsFragment.getRecordTakingBean();
                        mAgoraAPI.queryUserStatus(mRecordTakingBean.getData().getZjPhone());

                    }else {
                        MyToast.show("网络错误");
                    }
                }*/

               /* Intent intent=new Intent(FieledMissionsActivity.this, ConsultationActivity.class);
                intent.putExtra("jmid",jmid);
                intent.putExtra("jzid",jzid);
                startActivity(intent);*/
                break;
            case R.id.tv_trans:  //转诊
                showBottomDialog();
                break;
            case R.id.tv_trans_rollout:  //转出
                dialog.dismiss();
                if(!haverollout){
                    Intent intent1=new Intent(FieledMissionsActivity.this,RollOutActivity.class);
                    intent1.putExtra("jmid",jmid);
                    intent1.putExtra("jzid",jzid);
                    startActivity(intent1);
                }else{
                    Toast.makeText(FieledMissionsActivity.this,"该居民已经办理过转出手续了",Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.tv_trans_rollin://转入
                dialog.dismiss();
                if(!haverollin){
                        Intent intent2=new Intent(FieledMissionsActivity.this,RollInActivity.class);
                        intent2.putExtra("jmid",jmid);
                        intent2.putExtra("jzid",jzid);
                        startActivity(intent2);
                }else{
                  Toast.makeText(FieledMissionsActivity.this,"该居民已经办理过转入手续了",Toast.LENGTH_SHORT).show();
                }
                break;
        }
    }
    /**
     * 底部弹出框
     */
    Dialog dialog;
    private void showBottomDialog(){
        dialog = new Dialog(FieledMissionsActivity.this, R.style.dialog);
        View view_dialog = LayoutInflater.from(FieledMissionsActivity.this).inflate(
                R.layout.trans_bottom_dialog, null);
        TextView tv_trans_rollin=view_dialog.findViewById(R.id.tv_trans_rollin);
        tv_trans_rollin.setOnClickListener(this);
        TextView tv_trans_rollout=view_dialog.findViewById(R.id.tv_trans_rollout);
        tv_trans_rollout.setOnClickListener(this);
        TextView tv_trans_cancle=view_dialog.findViewById(R.id.tv_trans_cancle);
        tv_trans_cancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        dialog.setContentView(view_dialog);
        Window dialogWindow = dialog.getWindow();
        //设置位置
        dialogWindow.setGravity(Gravity.BOTTOM);
        //设置dialog的宽高属性
        dialogWindow.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        dialog.show();
    }
}
